package com.eii.system.controller;

import cn.hutool.core.bean.BeanUtil;
import com.eii.common.annotation.LoginUser;
import com.eii.common.constant.UserConstants;
import com.eii.common.model.auth.SysUser;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.common.web.page.PageResult;
import com.eii.excel.util.ExcelUtils;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.annotation.RequiresPermissions;
import com.eii.system.controller.vo.SysConfigExcel;
import com.eii.system.domain.SysConfig;
import com.eii.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 参数配置 信息操作处理
 */
@RestController
@RequestMapping("/config")
public class SysConfigController extends BaseController {

    private final static String CONTROLLER_TITLE = "参数配置";

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取参数配置列表
     */
    @RequiresPermissions("system:config:list")
    @GetMapping("/list")
    public PageResult<SysConfig> list(SysConfig config) {
        startPage();
        List<SysConfig> list = configService.selectConfigList(config);
        return getPageResult(list);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = "导出配置")
    @RequiresPermissions("system:config:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysConfig config) throws IOException {
        List<SysConfig> list = configService.selectConfigList(config);
        List<SysConfigExcel> sysConfigExcels = BeanUtil.copyToList(list, SysConfigExcel.class);
        String datestr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String filename = "参数数据" + datestr + ".xlsx";
        ExcelUtils.exportExcelStream(response, filename, SysConfigExcel.class, sysConfigExcels);
    }

    /**
     * 根据参数编号获取详细信息
     */
    @GetMapping(value = "/{configId}")
    public Result<SysConfig> getInfo(@PathVariable Long configId) {
        return Result.success(configService.selectConfigById(configId));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public Result<String> getConfigKey(@PathVariable String configKey) {
        return Result.success(configService.selectConfigByKey(configKey));
    }

    /**
     * 新增参数配置
     */
    @RequiresPermissions("system:config:add")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'新增:' + #config.configName")
    @PostMapping
    public Result<?> add(@Validated @RequestBody SysConfig config, @LoginUser SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
            return Result.fail("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(user.getUsername());
        return toResult(configService.insertConfig(config));
    }

    /**
     * 修改参数配置
     */
    @RequiresPermissions("system:config:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'更新:' + #config.configName")
    @PutMapping
    public Result<?> edit(@Validated @RequestBody SysConfig config, @LoginUser SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
            return Result.fail("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(user.getUsername());
        return toResult(configService.updateConfig(config));
    }

    /**
     * 删除参数配置
     */
    @RequiresPermissions("system:config:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = "'删除:' + #configIds")
    @DeleteMapping("/{configIds}")
    public Result<?> remove(@PathVariable Long[] configIds) {
        configService.deleteConfigByIds(configIds);
        return Result.success();
    }

    /**
     * 刷新参数缓存
     */
    @RequiresPermissions("system:config:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = "刷新参数缓存")
    @DeleteMapping("/refreshCache")
    public Result<?> refreshCache() {
        configService.resetConfigCache();
        return Result.success();
    }
}
